package base.tools;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.Calendar;
import java.util.Properties;
import java.util.Random;
import java.util.StringTokenizer;
import java.util.Vector;

import javax.servlet.http.HttpServletRequest;

import base.Power;

public class Tools {
	public static final String SPAN_START = "<span style=color:red>";
	public static final String SPAN_END = "</span>";
	public static final String B_START = "<b>";
	public static final String B_END = "</b>";

	public static String replace(String oldstr, String str1, String str2) {
		String tmpstr = oldstr;
		if (tmpstr != null) {
			tmpstr = tmpstr.replaceAll(str1, str2);
		}
		return tmpstr;
	}

	public static String[] split(String strT, String strB) {
		Vector<String> vct = new Vector<String>();
		if (strT == null || strT.trim().length() == 0)
			return null;

		int intStart = 0, intEnd = 0;
		while (strT.indexOf(strB, intStart) > -1) {
			intEnd = strT.indexOf(strB, intStart);
			vct.add(strT.substring(intStart, intEnd));
			intStart = ++intEnd;
		}
		vct.add(strT.substring(intEnd));
		return (String[]) vct.toArray(new String[vct.size()]);
	}

	/**
	 * 
	 * ���ű����ְ����ȷ��ȡ
	 * 
	 * @param scr
	 * @param length
	 * @param tail
	 * @return
	 */
	public static String cutStringBoldfaced(String scr, int length, String tail) {
		boolean fSpan = false, fB = false;
		if (scr != null) {
			if (scr.indexOf(SPAN_END) != -1) {
				fSpan = true;
				scr = scr.replaceAll(SPAN_END, "").replaceAll(SPAN_START, "");
			}
			if (scr.indexOf(B_END) != -1) {
				fB = true;
				scr = scr.replaceAll(B_END, "").replaceAll(B_START, "");
			}

			if (scr.length() > length) {
				scr = scr.substring(0, length);
			}
			if (tail != null && tail.length() > 0) {
				if (tail.equals("..."))
					scr = scr.substring(0, scr.length() - 2) + "...";
				else
					scr = scr + tail;
			}

			if (fSpan)
				scr = SPAN_START + scr + SPAN_END;
			if (fB)
				scr = B_START + scr + B_END;
			return scr;
		} else {
			return "";
		}
	}

	/**
	 * ����С���� lengthλ
	 * 
	 * @param scr
	 * @param length
	 * @return
	 */
	public static String cutDecimal(String scr, int length) {
		String aim = scr;

		if (scr != null) {
			if (scr.indexOf('.') > 0) {
				if (length == 0) {
					aim = scr.substring(0, scr.indexOf('.'));
				} else {
					String zheng = scr.substring(0, scr.indexOf('.'));
					String xiao = scr.substring(scr.indexOf('.'), scr.length());
					if (xiao.length() > length) {
						xiao = xiao.substring(0, length + 1);
					}
					aim = zheng + xiao;
				}
			}

		}

		return aim;
	}

	/**
	 * ȥ��"&",��","l��
	 * 
	 * @param oldStr
	 * @param oldSeparate
	 * @param newSeparate
	 */
	public static String replaceAnd(String oldStr, String oldSeparate,
			String newSeparate) {
		String ret = "";
		if (oldStr != null) {

			ret = oldStr;

			ret = ret.replaceAll(oldSeparate, newSeparate);

			if (ret.startsWith(newSeparate))
				ret = ret.substring(newSeparate.length());
			if (ret.endsWith(newSeparate))
				ret = ret.substring(0, ret.length() - newSeparate.length());

		}
		return ret;
	}

	/**
	 * ȥ��"&"
	 * 
	 * @param oldStr
	 */
	public static String replaceAnd(String oldStr) {
		String ret = "";

		String temp[] = null;

		if (oldStr != null) {

			temp = oldStr.split("&");

			for (int i = 0; i < temp.length; i++) {
				ret += temp[i];
			}

		}
		return ret;
	}

	/**
	 * ������������
	 * 
	 * @param passwdLen
	 *            ���볤��
	 * @return ����
	 */
	public static String generatePasswd(int passwdLen) {

		/**
		 * Ҫ���ص��������
		 */
		String passwd = "";

		// ��������
		String[] passChar = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };

		// �����
		Random r = new Random(System.currentTimeMillis());

		// �����������
		for (int i = 0; i < passwdLen; i++) {
			passwd += passChar[r.nextInt(10)];
		}

		return passwd;

	}

	public static boolean getifzhw() {
		// ϵͳ�ں��ж�
		Properties prop = System.getProperties();
		if (prop.getProperty("file.encoding").toUpperCase().equals("GBK")
				|| prop.getProperty("file.encoding").toUpperCase().equals(
						"GB2312"))
			return true;
		else
			return false;
		// ϵͳ�ں��ж�
	}

	public static String StrToHtml(String oldString) {
		if (oldString != null) {
			// String newString = "";
			oldString = oldString.replaceAll(String.valueOf(' '), "&nbsp;")
					.replaceAll(String.valueOf('\n'), "<br>");
			oldString = oldString.replaceAll(String.valueOf('\r'), "");
			return oldString;
		}
		return "";
	}

	public static String purgeSpecialNotation(String origin) {
		if (origin != null)
			return origin.replaceAll(String.valueOf(' '), "").replaceAll(
					String.valueOf('\n'), "").replaceAll(String.valueOf('\r'),
					"").replaceAll("<br>", "").replaceAll("<br />", "")
					.replaceAll("&nbsp;", "").replaceAll("\"", "").replaceAll(
							"\'", "");
		else
			return "";
	}

	public static String HtmlToStr(String html) {
		if (html != null) {
			html = html.replaceAll("&nbsp;", String.valueOf(' ')).replaceAll(
					"<br>", String.valueOf('\n'));
			return html;
		}
		return "";
	}

	public static String toByteName(String inStr) throws Exception {
		byte[] b = inStr.getBytes("GBK");
		String outStr = "";
		char tmpchar = ' ';

		for (int i = 0; i < b.length; i++) {
			if (b[i] < 0) {
				outStr = outStr + "%" + Integer.toHexString(256 + b[i]);
			} else {
				tmpchar = (char) b[i];
				outStr = outStr + tmpchar;
			}
		}
		return outStr;
	}

	public static String getDate(String days, boolean fill) {
		Calendar rightNow = Calendar.getInstance();
		if (days != null && !days.equals("") && !days.equals("0")) {
			long time = rightNow.getTime().getTime() - Long.parseLong(days)
					* 24 * 60 * 60 * 1000;
			rightNow.setTimeInMillis(time);
		}
		int year = rightNow.get(Calendar.YEAR);
		int month = rightNow.get(Calendar.MONTH) + 1;
		int day = rightNow.get(Calendar.DATE);
		return year + "-" + ((fill && month < 10) ? "0" : "") + month + "-"
				+ ((fill && day < 10) ? "0" : "") + day;
	}

	public static String GbToUtf8(String ret)
			throws UnsupportedEncodingException {
		String str = null;
		if (ret != null)
			str = new String(ret.getBytes("GBK"), "utf-8");
		return str;
	}

	/**
	 * ��weblogicȺ���ﷵ�ؿͻ��������ip��ַ
	 * 
	 * @param
	 * @return ip
	 */
	public static String getIpAddr(Power power) {
		String ip = power.getRequest().getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = power.getRequest().getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = power.getRequest().getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = power.getRequest().getRemoteAddr();
		}
		return ip;
	}

	/**
	 * ȥ���ַ��е�html����
	 * 
	 * @param str
	 *            String
	 * @return String
	 */
	public static String cutHtmlCode(String str) {
		if (str == null || str.equals(""))
			return "";
		else
			return str.replaceAll(
					"<\\s*\\/*[a-zA-Z]+[^>]*[^\\x00-\\xff]*[^>]*>", "");
	}

	/*******
	 * ���·��
	 * 
	 * @param request
	 * @return
	 */
	public static String getPath(HttpServletRequest request) {
		return request.getContextPath();
	}

	/*******
	 * �������
	 * 
	 * @param request
	 * @return
	 */
	public static String getDomain(HttpServletRequest request) {
		return request.getScheme() + "://" + request.getServerName() + ":"
				+ request.getServerPort();
	}

	/*********
	 * ���ȫ·��
	 * 
	 * @param request
	 * @return
	 */
	public static String getBasePath(HttpServletRequest request) {
		return getDomain(request) + getPath(request);
	}

	public static String getStringFromStrings(String[] strs, String spl) {
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < strs.length; i++) {
			sb.append(strs[i]).append(spl);
		}
		sb.deleteCharAt(sb.lastIndexOf(spl));
		return sb.toString();
	}

	public static String fileSizeFormat(String lnFileSize) {
		double douReturnValue;
		String returnValue;
		String a;
		double lonGB;
		double lonMB;
		double lonKB;
		douReturnValue = 0.0D;
		double size = 0.0D;
		returnValue = "";
		a = "";
		lonGB = 1073741824D;
		lonMB = 1048576D;
		lonKB = 1024D;
		size = Double.parseDouble(lnFileSize);
		if (size >= lonGB) {
			douReturnValue = size / lonGB;
			a = "GB";
		} else if (size >= lonMB) {
			douReturnValue = size / lonMB;
			a = "MB";
		} else if (size >= lonKB) {
			douReturnValue = size / lonKB;
			a = "KB";
		} else {
			douReturnValue = size;
			a = "B&nbsp;";
		}
		returnValue = Double.toString(Math.round(douReturnValue)) + a;

		return returnValue;
	}

	public static String cutString(String source, String spl, int index)
			throws Exception {
		return source
				.substring(source.indexOf(spl, index) + 1, source.length());
	}

	// ȥ��ͷ���ͽ�β��
	public static String cutBeginAndEndString(String source, String spl)
			throws Exception {

		if (source.startsWith(spl)) {
			source = cutString(source, spl, 0);
		}
		if (source.lastIndexOf(spl) + 1 == source.length()) {
			source = source.substring(0, source.length() - 1);
		}
		return source;
	}

	public static String[] splitToArray(String oldStr, String token) {
		StringTokenizer oldToken = new StringTokenizer(oldStr, token);
		int len = oldToken.countTokens();
		String arr[] = new String[len];
		for (int i = 0; oldToken.hasMoreElements(); i++) {
			String newStr = oldToken.nextToken();
			arr[i] = newStr;
		}

		return arr;
	}

	public static String transferFileSeperator(String path, String type2) {
		type2 = type2.toLowerCase();
		if (type2.equals("local"))
			return Replace(path, "/", File.separator);
		if (type2.equals("http"))
			return Replace(path, File.separator, "/");
		else
			return path;
	}

	public static String Replace(String source, String oldString,
			String newString) {
		StringBuffer output = new StringBuffer();
		int lengthOfSource = source.length();
		int lengthOfOld = oldString.length();
		int posStart = 0;
		if (source.indexOf(oldString) == -1)
			return source;
		int pos;
		while ((pos = source.indexOf(oldString, posStart)) >= 0) {
			output.append(source.substring(posStart, pos));
			output.append(newString);
			posStart = pos + lengthOfOld;
		}
		if (posStart < lengthOfSource)
			output.append(source.substring(posStart));
		return output.toString();
	}

	public static String getLastInsertID(Power power) throws Exception {
		return power.getMapFromSql("SELECT LAST_INSERT_ID() as id").get("ID")
				.toString();
	}

}
